package com.xxl.sso.server.service.impl;

import cn.hutool.core.swing.ScreenUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxl.sso.server.core.model.User;
import com.xxl.sso.server.core.result.ReturnT;
import com.xxl.sso.server.mapper.UserMapper;
import com.xxl.sso.server.service.UserService;
import jdk.nashorn.api.scripting.ScriptUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

//  假数据
    private static List<User> mockUserList = new ArrayList<>();
    static {
        for (int i = 0; i <5; i++) {
            User User = new User();
            User.setId((long) (1000 +i));
            User.setUsername("user" + (i>0?String.valueOf(i):""));
            User.setPassword("123456");
            mockUserList.add(User);
        }
    }

    @Override
    public ReturnT<User> findUser(String username, String password) {

        if (username==null || username.trim().length()==0) {
            return new ReturnT<User>(ReturnT.FAIL_CODE, "请输入用户名！");
        }
        if (password==null || password.trim().length()==0) {
            return new ReturnT<User>(ReturnT.FAIL_CODE, "请输入密码！");
        }

        // mock user
        // 用户认证校验核心代码
//        for (User mockUser: mockUserList) {
//            if (mockUser.getUsername().equals(username) && mockUser.getPassword().equals(password)) {
//                return new ReturnT<User>(mockUser);
//            }
//        }
        //1. 根据用户名查询是否存在该用户
        User user = baseMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if(user != null) {
            // 2 将密码进行md5加密
            String passwordmd5 = SecureUtil.md5(password);
            // 3 判断密码是否正确
            if(user.getPassword().equals(passwordmd5)) {
                return new ReturnT<>(user);
            }
        }

        return new ReturnT<User>(ReturnT.FAIL_CODE, "用户名或密码无效！");
    }


}
